package com.app.campusguide;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.app.sqlite_connect.HandlerSqlite;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Schedule_activity extends Activity {
	private final String APP_LOG = "Schedule_activity";
	private HandlerSqlite database;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_schedule_program);
		database = new HandlerSqlite(this);
		initViews();
		initButtons();
	}

	/**
	 * In this method initializes all views and lists are filled
	 */
	private void initViews()	{
		TextView txtv_class_name = (TextView)findViewById(R.id.txt_name_class);
		Spinner spn_crate_day_of_week = (Spinner)findViewById(R.id.spn_create_day_week);
		Spinner spn_create_start_hour = (Spinner)findViewById(R.id.spn_create_start_hour);
		Spinner spn_create_end_hour = (Spinner)findViewById(R.id.spn_create_end_hour);
		Spinner spn_create_hall = (Spinner)findViewById(R.id.spn_create_hall);
		
		ArrayAdapter<?> adp_day_of_week = ArrayAdapter.createFromResource(this, R.array.days_name,android.R.layout.simple_spinner_item);
		adp_day_of_week.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spn_crate_day_of_week.setAdapter(adp_day_of_week);
		
		ArrayAdapter<?> adp_start_hour = ArrayAdapter.createFromResource(this, R.array.start_hours,android.R.layout.simple_spinner_item);
		adp_start_hour.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spn_create_start_hour.setAdapter(adp_start_hour);
		
		ArrayAdapter<?> adp_end_hour = ArrayAdapter.createFromResource(this, R.array.end_hours,android.R.layout.simple_spinner_item);
		adp_end_hour.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spn_create_end_hour.setAdapter(adp_end_hour);
		
		ArrayAdapter<?> adp_hall = ArrayAdapter.createFromResource(this, R.array.name_site,android.R.layout.simple_spinner_item);
		adp_hall.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spn_create_hall.setAdapter(adp_hall);
		
		TextView txt_label_name_class = (TextView)findViewById(R.id.txt_lbl_class_name);
		TextView txt_label_day_of_week = (TextView)findViewById(R.id.txt_lbl_day_of_week);
		TextView txt_label_start_hour = (TextView)findViewById(R.id.txt_lbl_start_hour);
		TextView txt_label_end_hour = (TextView)findViewById(R.id.txt_lbl_end_hour);
		TextView txt_label_hall = (TextView)findViewById(R.id.txt_lbl_hall);
		txt_label_name_class.setTextColor(Color.BLACK);
		txt_label_day_of_week.setTextColor(Color.BLACK);
		txt_label_start_hour.setTextColor(Color.BLACK);
		txt_label_end_hour.setTextColor(Color.BLACK);
		txt_label_hall.setTextColor(Color.BLACK);
		
		
		txtv_class_name.setOnFocusChangeListener(new OnFocusChangeListener() {
		    public void onFocusChange(View v, boolean hasFocus) {
		    	if(!hasFocus){
		    		TextView txtv_class_name = (TextView)findViewById(R.id.txt_name_class);
		    		@SuppressWarnings("static-access")
					InputMethodManager imm = (InputMethodManager)getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
		    		imm.hideSoftInputFromWindow(txtv_class_name.getWindowToken(), 0);
		    	}

		    }
		});
    }

	/**
	 * Establishing the behavior of the buttons touch
	 */
	private void initButtons()	{
		Button btn_create_acept =(Button) findViewById(R.id.btn_accept);
		Button btn_create_clear =(Button) findViewById(R.id.btn_clear);
		
		btn_create_clear.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
        		cleanViews();
            }      
        });
		
		btn_create_acept.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	try {
					insertRow();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }      
        });
	}
	
	/**
	 * Clean views for a new row
	 */
	private void cleanViews(){
		TextView txtv_class_name = (TextView)findViewById(R.id.txt_name_class);
		txtv_class_name.setText("");
		Spinner spn_crate_day_of_week = (Spinner)findViewById(R.id.spn_create_day_week);
		spn_crate_day_of_week.setSelection(0);
		Spinner spn_create_start_hour = (Spinner)findViewById(R.id.spn_create_start_hour);
		spn_create_start_hour.setSelection(0);
		Spinner spn_create_end_hour = (Spinner)findViewById(R.id.spn_create_end_hour);
		spn_create_end_hour.setSelection(0);
		Spinner spn_create_hall = (Spinner)findViewById(R.id.spn_create_hall);
		spn_create_hall.setSelection(0);
	}
	
	/**
	 * First validate information, when data is ok call insert class method for SQLite manager. If exists any mistake or absence in data
	 * the label field is highlight with red color
	 * @throws ParseException
	 */
	private void insertRow() throws ParseException{
		TextView txtv_class_name = (TextView)findViewById(R.id.txt_name_class);
		TextView txt_label_name_class = (TextView)findViewById(R.id.txt_lbl_class_name);
		TextView txt_label_day_of_week = (TextView)findViewById(R.id.txt_lbl_day_of_week);
		TextView txt_label_start_hour = (TextView)findViewById(R.id.txt_lbl_start_hour);
		TextView txt_label_end_hour = (TextView)findViewById(R.id.txt_lbl_end_hour);
		TextView txt_label_hall = (TextView)findViewById(R.id.txt_lbl_hall);
		Spinner spn_crate_day_of_week = (Spinner)findViewById(R.id.spn_create_day_week);
		Spinner spn_create_start_hour = (Spinner)findViewById(R.id.spn_create_start_hour);
		Spinner spn_create_end_hour = (Spinner)findViewById(R.id.spn_create_end_hour);
		Spinner spn_create_hall = (Spinner)findViewById(R.id.spn_create_hall);
		if(isDataComplete())
		{
			if(isHoursOk())
			{
				long l_result_insert = database.insertRowOnSchedule(txtv_class_name.getText().toString().trim(), 
						((Integer)spn_crate_day_of_week.getSelectedItemPosition()).toString(), 
						spn_create_start_hour.getSelectedItem().toString().trim(), 
						spn_create_end_hour.getSelectedItem().toString().trim(),
						spn_create_hall.getSelectedItem().toString().trim());
				if(l_result_insert >= 0){
					TextView text1 = new TextView(getApplicationContext());
			    	text1.setText(R.string.str_row_inserted);
			    	showToast (text1.getText().toString());
			    	text1 = null;
				}else{
					if(l_result_insert == -1 || l_result_insert == -3 || l_result_insert == -4){
						TextView text1 = new TextView(getApplicationContext());
				    	text1.setText(R.string.str_unexpected_error);
				    	showToast (text1.getText().toString());
				    	text1 = null;
					}
					if(l_result_insert == -2){
						TextView text1 = new TextView(getApplicationContext());
				    	text1.setText(R.string.str_not_allow_cross_classes);
				    	showToast (text1.getText().toString());
				    	text1 = null;
					}
				}
				txt_label_name_class.setTextColor(Color.BLACK);
				txt_label_day_of_week.setTextColor(Color.BLACK);
				txt_label_start_hour.setTextColor(Color.BLACK);
				txt_label_end_hour.setTextColor(Color.BLACK);
				txt_label_hall.setTextColor(Color.BLACK);
			}else{
				txt_label_start_hour.setTextColor(Color.RED);
				txt_label_end_hour.setTextColor(Color.RED);
				TextView text1 = new TextView(getApplicationContext());
		    	text1.setText(R.string.str_hour_error);
		    	showToast (text1.getText().toString());
		    	text1 = null;
			}
			
		}else
		{
			txt_label_start_hour.setTextColor(Color.RED);
			txt_label_end_hour.setTextColor(Color.RED);
			TextView text1 = new TextView(getApplicationContext());
	    	text1.setText(R.string.str_most_asign_values);
	    	showToast (text1.getText().toString());
	    	text1 = null;
			if(txtv_class_name.getText().toString().isEmpty()){
				txt_label_name_class.setTextColor(Color.RED);
			}
			if(spn_crate_day_of_week.getSelectedItem() == null){
				txt_label_day_of_week.setTextColor(Color.RED);
			}
			if(spn_create_start_hour.getSelectedItem() == null){
				txt_label_start_hour.setTextColor(Color.RED);
			}
			if(spn_create_end_hour.getSelectedItem() == null){
				txt_label_end_hour.setTextColor(Color.RED);
			}
			if(spn_create_hall.getSelectedItem() == null){
				txt_label_hall.setTextColor(Color.RED);
			}
		}
	}
	
	/**
	 * Verify if all fields on form is filled
	 * @return True if all fields are filled, otherwise return False
	 */
	private boolean isDataComplete(){
		boolean b_return = false;
		
		Spinner spn_crate_day_of_week = (Spinner)findViewById(R.id.spn_create_day_week);
		Spinner spn_create_start_hour = (Spinner)findViewById(R.id.spn_create_start_hour);
		Spinner spn_create_end_hour = (Spinner)findViewById(R.id.spn_create_end_hour);
		Spinner spn_create_hall = (Spinner)findViewById(R.id.spn_create_hall);
		TextView txtv_class_name = (TextView)findViewById(R.id.txt_name_class);
		if((!txtv_class_name.getText().toString().isEmpty()) && (spn_crate_day_of_week.getSelectedItem() != null)
			&& (spn_create_start_hour.getSelectedItem() != null) && (spn_create_end_hour.getSelectedItem() != null)
			&& (spn_create_hall.getSelectedItem() != null)){
			b_return = true;
		}			
		return b_return;
	}
	
	/**
	 * Verify if hours selected for start and end are valid. Start hour must be less than end hour.
	 * @return True if hours is correct otherwise, return False
	 * @throws ParseException
	 */
	@SuppressLint("SimpleDateFormat")
	private boolean isHoursOk() throws ParseException{
		boolean b_return = true;
		Spinner spn_create_start_hour = (Spinner)findViewById(R.id.spn_create_start_hour);
		Spinner spn_create_end_hour = (Spinner)findViewById(R.id.spn_create_end_hour);
		String str_start_hour = spn_create_start_hour.getSelectedItem().toString();
		String str_end_hour = spn_create_end_hour.getSelectedItem().toString();
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
		java.util.Date dt_start_hour;
		java.util.Date dt_end_hour;
		dt_start_hour = dateFormat.parse(str_start_hour.trim());
		dt_end_hour = dateFormat.parse(str_end_hour.trim());
		if (dt_start_hour.compareTo(dt_end_hour) < 0) {
		    b_return = true;
		} else {
			b_return = false;
		}
		return b_return;
	}

	/**
	 * This method show an alert message with Toast class
	 * @param str_message String message to show on Toast
	 */
	private void showToast(String str_message){
		Toast toast = Toast.makeText(getApplicationContext(), str_message, Toast.LENGTH_LONG);
		View textView = toast.getView();
		LinearLayout lay = new LinearLayout(getApplicationContext());
		lay.setOrientation(LinearLayout.HORIZONTAL);
		ImageView view = new ImageView(getApplicationContext());
		view.setImageResource(android.R.drawable.ic_menu_info_details);
		lay.addView(view);
		lay.addView(textView);
		toast.setView(lay);
		toast.show();
	}
}
